package com.qfmy.mystation.ui.adapter;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.qfmy.mystation.MyStationApp;
import com.qfmy.mystation.R;
import com.qfmy.mystation.bean.LiveWallpaperBean;
import com.qfmy.mystation.dbHelper.WallpaperDBHelper;
import com.qfmy.mystation.service.VideoWallpaperService;
import com.qfmy.mystation.utils.SaveUtils;
import com.qfmy.mystation.utils.ToastUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import timber.log.Timber;

public class LiveHorizontalVpAdapter extends RecyclerView.Adapter<LiveHorizontalVpAdapter.HorizontalVpViewHolder> {
    private final Context mContext;
    private List<LiveWallpaperBean.DataDTO.ListDTO> wallpapers;

    public LiveHorizontalVpAdapter(Context context, List<LiveWallpaperBean.DataDTO.ListDTO> wallpapers) {
        mContext = context;
        this.wallpapers = wallpapers;
    }

    @NonNull
    @Override
    public HorizontalVpViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new HorizontalVpViewHolder(LayoutInflater.from(mContext).inflate((R.layout.item_live_detail), parent, false));
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull HorizontalVpViewHolder holder, int position) {
        LiveWallpaperBean.DataDTO.ListDTO bean = wallpapers.get(position);
        Glide.with(mContext).load(bean.getPreview()).into(holder.iv_cover);

        MediaController mediaController = new MediaController(mContext);
        mediaController.setVisibility(View.INVISIBLE);
        holder.live.setMediaController(mediaController);
        String proxyUrl = MyStationApp.proxy.getProxyUrl(bean.getUrl());
        holder.live.setVideoPath(proxyUrl);
        holder.live.requestFocus();
        holder.live.setOnPreparedListener(mediaPlayer -> {
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
            TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f);
            hideAnim.setDuration(500);
            holder.fl_cover.startAnimation(hideAnim);
            holder.fl_cover.setVisibility(View.GONE);
        });

        holder.live.setOnClickListener(view -> {
            if (holder.SHOW) {
                holder.fl_footer.setVisibility(View.VISIBLE);
                holder.btn_download.setVisibility(View.VISIBLE);
                holder.btn_collection.setVisibility(View.VISIBLE);
                holder.SHOW = false;
            } else {
                holder.fl_footer.setVisibility(View.GONE);
                holder.btn_download.setVisibility(View.GONE);
                holder.btn_collection.setVisibility(View.GONE);
                holder.SHOW = true;
            }
        });
        holder.set_as_lock_paper.setOnClickListener(view -> {
            boolean flag = copyFile(proxyUrl.replace("file://", ""), Objects.requireNonNull(mContext.getExternalCacheDir()
                    .getParentFile()).getAbsolutePath() + "/livewallpaper/mylivewallpaper.mp4");
            System.out.println(flag);
            setToWallPaper(mContext);
            ToastUtils.shortToast("动态壁纸设置成功");
        });
//        holder.set_as_desktop_paper.setOnClickListener(view -> {
//            holder.img.buildDrawingCache();
//            Bitmap bitmap = holder.img.getDrawingCache();
//            SetWallpaperUtil.setWallpaper(mContext, bitmap, SetWallpaperUtil.FLAG_SYSTEM);
//            ToastUtils.shortToast("桌面壁纸设置成功");
//        });

        holder.btn_download.setOnClickListener(view -> {
            SaveUtils.saveVideoToAlbum(mContext, proxyUrl.replace("file://", ""));
            Toast.makeText(mContext, "视频成功保存到相册", Toast.LENGTH_SHORT).show();
            WallpaperDBHelper.insert(mContext, bean.getTag(), bean.getUrl(), "", 0,
                    WallpaperDBHelper.TYPE_DOWNLOAD);
        });
        holder.btn_collection.setOnClickListener(view -> {
            Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
            WallpaperDBHelper.insert(mContext, bean.getTag(), bean.getUrl(), null, 0,
                    WallpaperDBHelper.TYPE_COLLECTION);
        });
        if (!TextUtils.isEmpty(bean.getTag())) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            holder.rv_tag.setLayoutManager(linearLayoutManager);
            holder.rv_tag.setAdapter(new TagListAdapter(bean.getTag().split(","), R.layout.item_tag_detail));
        }
    }

    @Override
    public int getItemCount() {
        return wallpapers == null ? 0 : wallpapers.size();
    }

    public static void setToWallPaper(Context context) {
        try {
            WallpaperManager.getInstance(context).clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                new ComponentName(context, VideoWallpaperService.class));
        context.startActivity(intent);
    }

    public static boolean copyFile(String oldPathName, String newPathName) {
        try {
            File newFile = new File(newPathName);
            if (!Objects.requireNonNull(newFile.getParentFile()).exists()) {
                newFile.getParentFile().mkdirs();
            }
            File oldFile = new File(oldPathName);
            System.out.println(oldPathName);
            if (!oldFile.exists()) {
                Timber.tag("copyFile").e("copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                Timber.tag("copyFile").e("copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                Timber.tag("copyFile").e("copyFile:  oldFile cannot read.");
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(oldPathName);
            FileOutputStream fileOutputStream = new FileOutputStream(newPathName);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    class HorizontalVpViewHolder extends RecyclerView.ViewHolder {
        Boolean SHOW = true;
        VideoView live;
        ImageView iv_cover;
        Button set_as_lock_paper, set_as_desktop_paper;
        RecyclerView rv_tag;
        FrameLayout fl_footer;
        ImageButton btn_download;
        ImageButton btn_collection;
        FrameLayout fl_cover;

        HorizontalVpViewHolder(@NonNull View itemView) {
            super(itemView);
            live = itemView.findViewById(R.id.live_detail);
            set_as_lock_paper = itemView.findViewById(R.id.set_as_lock_paper);
            set_as_desktop_paper = itemView.findViewById(R.id.set_as_desktop_paper);
            rv_tag = itemView.findViewById(R.id.rv_tag);
            fl_footer = itemView.findViewById(R.id.footer);
            btn_download = itemView.findViewById(R.id.btn_download);
            btn_collection = itemView.findViewById(R.id.btn_collection);
            iv_cover = itemView.findViewById(R.id.iv_cover);
            fl_cover = itemView.findViewById(R.id.fl_cover);
        }
    }
}

